package com.myfoon.servlet.accounts;

import com.myfoon.model.ejb.UserEJBLocal;
import com.myfoon.model.entity.Country;
import com.myfoon.model.entity.User;

import com.myfoon.model.entity.UserPi;

import com.myfoon.utils.CalendarUtils;

import java.io.IOException;

import java.util.Iterator;
import java.util.Map;

import javax.ejb.EJB;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Register extends HttpServlet {
    @EJB
    UserEJBLocal userLocal;
    
    public Register() {
    }

    @Override
    protected void doPost(HttpServletRequest httpServletRequest,
                          HttpServletResponse httpServletResponse) throws ServletException,
                                                                          IOException {        
        User user = new User();        
        String su_gender = httpServletRequest.getParameter("su_gender");
        String su_country  = httpServletRequest.getParameter("su_country");
        String su_email = httpServletRequest.getParameter("su_email");
        String su_year = httpServletRequest.getParameter("su_year");
        String su_month = httpServletRequest.getParameter("su_month");
        String su_day = httpServletRequest.getParameter("su_day");
        String su_fullname = httpServletRequest.getParameter("su_fullname");
        String su_password = httpServletRequest.getParameter("su_password");
        
        user.setEmail(su_email);        
        user.setPasswd(su_password);
        user.setStatus((short)1);
        
        UserPi userPi = new UserPi();
        userPi.setFullname(su_fullname);
        userPi.setGender(new Boolean(su_gender));
        userPi.setCountry(new Country(new Integer(su_country)));
        userPi.setBirthdate(CalendarUtils.createDate(Integer.parseInt(su_year), Integer.parseInt(su_month), Integer.parseInt(su_day)));        
        
        user.setUserPi(userPi);
        
        try {
            user = userLocal.persist(user);    
            httpServletRequest.getSession(true).setAttribute("user", user);
            httpServletResponse.sendRedirect("/home.jsp");
        }
        catch(Exception e) {            
            e.printStackTrace();
            httpServletResponse.sendRedirect("/error#1");
        }
        
    }
}
